package cn.lix.sc.rpc.oauth2.service.impl;

import cn.lix.sc.rpc.oauth2.entity.TbPermission;
import cn.lix.sc.rpc.oauth2.entity.TbUser;
import cn.lix.sc.rpc.oauth2.service.TbPermissionService;
import cn.lix.sc.rpc.oauth2.service.TbUserService;
import com.google.common.collect.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    private final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(this.getClass());

    @Autowired
    private TbPermissionService permissionService;

    @Autowired
    private TbUserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 查询用户信息
        TbUser tbUser = userService.getByName(username);
        if (tbUser == null) {
            log.error("找不到该用户，用户名：" + username);
            throw new UsernameNotFoundException("找不到该用户，用户名：" + username);
        }

        // 获取用户授权
        List<TbPermission> permissions = permissionService.getPermissionByUserId(tbUser.getId());

        List<GrantedAuthority> grantedAuthorities = Lists.newArrayList();
        // 声明用户授权
        permissions.forEach(tbPermission -> {
            if (tbPermission != null && tbPermission.getEnname() != null) {
                grantedAuthorities.add(new SimpleGrantedAuthority(tbPermission.getEnname()));
            }
        });
        // 由框架完成认证工作
        return new User(tbUser.getUsername(), tbUser.getPassword(), grantedAuthorities);
    }
}
